# coding=utf-8
from db_model import DbModel, with_transaction


class DataSaver(object):

    @classmethod
    def save(cls, words_data):
        for word in words_data:
            with open('out.txt', 'a') as f:
                f.writelines(word.encode('utf-8'))
                f.writelines('\n')

            f.close()

    @classmethod
    def save_list(cls, words_content, level):
        for word in words_content:
            cls.save_profile(word, level)

    @classmethod
    @with_transaction
    def save_profile(cls, word, level):

        word_id = DbModel.select('word_list', ['word'], word.get('word').encode('utf-8'))

        if word_id is None:

            word_list = DbModel.save(
                'word_list',
                ['word', 'cn_mean', 'en_mean'],
                word.get('word').encode('utf-8'),
                word.get('cn_mean').encode('utf-8'),
                word.get('en_mean').encode('utf-8')
            )

            word_id, _ = word_list
        else:
            word_id = word_id[0]
        DbModel.save(
            'list_level',
            ['word_id', 'level_id'],
            int(word_id), level
        )

        word_annotation = word.get('annotation')

        for annotation in word_annotation:
            DbModel.save(
                'word_example',
                ['word_id', 'annotation', 'translation'],
                int(word_id), annotation.get('en').encode('utf-8'), annotation.get('cn').encode('utf-8')
            )

        return True
